const Koa = require('koa');
const app = new Koa();
const static = require('koa-static');
const bodyparser = require('koa-bodyparser');
const template = require('./utils/templating');
require('./utils/formatTime');
const route = require('./controllers');
const model = require('./models');
const session = require('./utils/session')


app.use(static(__dirname + '/public'))

app.use(session(app));

app.use(template)

app.use(bodyparser())

app.use(async (ctx, next) => {
    const allowpage = ['/user', '/api/user/login', '/api/user/register','/quest/writequest']

    if (allowpage.includes(ctx.path) || ctx.path.substring(0,ctx.path.lastIndexOf('/'))===allowpage[3]) {
        await next();
    }
    else{
        if(ctx.session.username){
            await next();
        }else{
            ctx.redirect('/user')
        }
    }
})

app.use(route.routes())


;(async ()=>{
    await model.sync()//模型同步

    await model.datainit();//数据初始化
})();


app.listen(3500, () => {
    console.log('http://localhost:3500');
})
